package com.example.yiwei.crm.view.activity.customerActivity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.customerDao;
import com.example.yiwei.crm.dao_impl.customerDaoImpl;
import com.example.yiwei.crm.data.GetContact;
import com.example.yiwei.crm.data.GetCustomerData;
import com.example.yiwei.crm.data.GetCustumer;
import com.example.yiwei.crm.data.GetPersonnal;
import com.example.yiwei.crm.entity.ContactMessageEntity;
import com.example.yiwei.crm.entity.CustomerMessageEntity;
import com.example.yiwei.crm.entity.personnalEntity;
import com.example.yiwei.crm.view.Class.listviewClass.AutoListView;
import com.example.yiwei.crm.view.Class.listviewClass.ListViewAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;


public class CustomerSimpleMessageActivity extends AppCompatActivity implements AutoListView.OnRefreshListener,AutoListView.OnLoadListener {
    List<CustomerMessageEntity> customers;
    int client_id;
    List<CustomerMessageEntity> customerlist;
    String result;
    List<CustomerMessageEntity> customerList;
    private ListViewAdapter adapter;
    MyAdapter ladapter;
    ImageView btn_back, btn_plus, btn_search;
    customerDao customer;
    boolean tag = false;
    private AutoListView lstv;
    private ListView listView;
    private Button btn_select;
    int customer_id;
    Intent intent;
    int page = 1;
    private ArrayAdapter spinner_adapter;
    List<String> spinner_list;
    private Spinner spinner;
    personnalEntity personnal;
    int adapterTag =0;
    int a=0;
    List<CustomerMessageEntity> customerList2;
    List<CustomerMessageEntity> customerList1;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            List<CustomerMessageEntity> result = (List<CustomerMessageEntity>) msg.obj;
            switch (msg.what) {
                case AutoListView.REFRESH:
                    lstv.onRefreshComplete();
                    customerList.clear();
                    customerList.addAll(result);
                    break;
                case AutoListView.LOAD:
                    lstv.onLoadComplete();
                    List<CustomerMessageEntity> list = new ArrayList<>();
                    list.addAll(customerList);
                    customerList.clear();
                    if (result!=null) {
                        customerList.addAll(result);
                    }
                    customerList.addAll(list);
                    break;
            }
            if (result!=null) {
//                lstv.setResultSize(result.size());
            }else{
//                lstv.setResultSize(0);
            }
            ladapter.notifyDataSetChanged();

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_simple_message);
        lstv = (AutoListView) findViewById(R.id.lstv);
        lstv.setDivider(new ColorDrawable(Color.rgb(216, 216, 216)));
        lstv.setDividerHeight(1);
        if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))) {
            lstv.setLoadEnable(false);
        }
        customerList = new ArrayList<>();
        spinner= (Spinner) findViewById(R.id.user_fragment_spinner);
        ladapter = new MyAdapter();
        lstv.setOnRefreshListener(this);
        lstv.setOnLoadListener(this);
        btn_back = (ImageView) findViewById(R.id.customerSimpleMessage_btn_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        btn_plus = (ImageView) findViewById(R.id.customerSimpleMessage_btn_plus);
        btn_select= (Button) findViewById(R.id.customer_btn_select);
        btn_select.setVisibility(View.GONE);
        btn_search = (ImageView) findViewById(R.id.customerSimpleMessage_btn_search);
        btn_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CustomerSimpleMessageActivity.this, CustomerAddActivity.class);
                if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))) {
                    intent.putExtra("kehuchiTag", "kehuchi");
                }
                startActivity(intent);

            }
        });
        personnal= GetPersonnal.get();
        spinner_list=new ArrayList<>();
        if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))) {
            spinner_list.add("全部客户");
        }else{
            spinner_list.add("全部客户");
            spinner_list.add("我的客户");
        }
        spinner_adapter=new ArrayAdapter(CustomerSimpleMessageActivity.this,android.R.layout.simple_spinner_item, spinner_list);
        spinner.setAdapter(spinner_adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if ("全部客户".equals(spinner_list.get(i))){
                    a=0;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            customer = new customerDaoImpl();
                            if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))) {
                                customerList = customer.querySimpleCustomerMessage(baseClass.find_all_customer_url+1, null);
                            } else {
                                customerList2 = customer.querySimpleCustomerMessage(baseClass.query_simple_customer_message_url+1, null);
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                    lstv.setLoadEnable(true);
//                                    listView= (ListView) findViewById(R.id.customr_list_select);
//                                    adapter= new ListViewAdapter(CustomerSimpleMessageActivity.this,customerList);
//                                    listView.setAdapter(adapter);
//                                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//                                    listView.setVisibility(View.GONE);
//                                    btn_select.setOnClickListener(new View.OnClickListener() {
//                                        @Override
//                                        public void onClick(View view) {
//                                            if (btn_select.getText().toString().equals("预约到院")){
//                                                ListViewAdapter.setState();
//                                                lstv.setVisibility(View.GONE);
//                                                listView.setVisibility(View.VISIBLE);
//                                                btn_select.setText("确定");
//                                                adapter.notifyDataSetChanged();
//                                            }else{
//                                                List<Integer> list = ListViewAdapter.getIDs();
//                                                if (list.size()==0){
//                                                    Toast.makeText(CustomerSimpleMessageActivity.this, "请选择您要预约的客户！", Toast.LENGTH_SHORT).show();
//                                                }else if (list.size()>1){
//                                                    Toast.makeText(CustomerSimpleMessageActivity.this, "一次只能预约一个客户！", Toast.LENGTH_SHORT).show();
//                                                }else if (list.size()==1){
//                                                    btn_select.setText("预约到院");
//                                                    listView.setVisibility(View.GONE);
//                                                    lstv.setVisibility(View.VISIBLE);
//                                                    Intent intent=new Intent(CustomerSimpleMessageActivity.this,CustomerAppointmentAcitity.class);
//                                                    intent.putExtra("customer_id",list.get(0));
//                                                    startActivity(intent);
//                                                }
//                                            }
//
//                                        }
//                                    });
                                    if (adapterTag==0){
                                        lstv.setAdapter(ladapter);
                                        adapterTag=1;
                                    }
                                    if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))){

                                    }else{
                                        customerList.clear();
                                        customerList.addAll(customerList2);
                                    }
                                    ladapter.notifyDataSetChanged();
                                    lstv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            final int client_id = customerList.get(customerList.size()-position).getClient_id();
                                            intent = new Intent(CustomerSimpleMessageActivity.this, CustomerDetailedMessageActivity.class);
                                            intent.putExtra("number", client_id);
                                            if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))) {
                                                intent.putExtra("kehuchiTag", "kehuchi");
                                                intent.putExtra("number", client_id);
                                            }
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    customerDao customerdao = new customerDaoImpl();
                                                    GetCustumer.customers = customerdao.queryDetailedCustomerMessage(baseClass.query_detailed_customer_message_url + client_id, null);
                                                    if ("success".equals(GetCustumer.customers.getTag())) {
                                                        List<ContactMessageEntity> contacts = customerdao.queryContactAllMessage(baseClass.find_all_contact + client_id, null);
                                                        for (int i = 0; i < contacts.size(); i++) {
                                                            if (1 == contacts.get(i).getIs_first_contact()) {
                                                                GetContact.create();
                                                                GetContact.contact = contacts.get(i);
                                                                tag = true;
                                                            }
                                                        }
                                                        if (contacts.size() == 0 || !tag) {
                                                            GetContact.create();
                                                        }
                                                        tag = false;
                                                        startActivity(intent);
                                                    } else {
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                Toast.makeText(CustomerSimpleMessageActivity.this, "数据加载失败", Toast.LENGTH_SHORT).show();
                                                            }
                                                        });
                                                    }


                                                }
                                            }).start();

                                        }
                                    });
                                }
                            });
                        }
                    }).start();

                }else if ("我的客户".equals(spinner_list.get(i))){
                    a=1;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            customerDao customerDao=new customerDaoImpl();
                             customerList1=new ArrayList<CustomerMessageEntity>();
                            customerList1=customerDao.queryMineAllCustomerMessage(baseClass.query_mine_customer_url+1,null);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                   lstv.setLoadEnable(false);
//                                    listView = (ListView) findViewById(R.id.customr_list_select);
//                                    adapter = new ListViewAdapter(CustomerSimpleMessageActivity.this, customerList);
//                                    listView.setAdapter(adapter);
//                                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//                                    listView.setVisibility(View.GONE);
//                                    btn_select.setOnClickListener(new View.OnClickListener() {
//                                        @Override
//                                        public void onClick(View view) {
//                                            if (btn_select.getText().toString().equals("预约到院")) {
//                                                ListViewAdapter.setState();
//                                                lstv.setVisibility(View.GONE);
//                                                listView.setVisibility(View.VISIBLE);
//                                                btn_select.setText("确定");
//                                                adapter.notifyDataSetChanged();
//                                            } else {
//                                                List<Integer> list = ListViewAdapter.getIDs();
//                                                if (list.size() == 0) {
//                                                    Toast.makeText(CustomerSimpleMessageActivity.this, "请选择您要预约的客户！", Toast.LENGTH_SHORT).show();
//                                                } else if (list.size() > 1) {
//                                                    Toast.makeText(CustomerSimpleMessageActivity.this, "一次只能预约一个客户！", Toast.LENGTH_SHORT).show();
//                                                } else if (list.size() == 1) {
//                                                    btn_select.setText("预约到院");
//                                                    listView.setVisibility(View.GONE);
//                                                    lstv.setVisibility(View.VISIBLE);
//                                                    Intent intent = new Intent(CustomerSimpleMessageActivity.this, CustomerAppointmentAcitity.class);
//                                                    intent.putExtra("customer_id", list.get(0));
//                                                    startActivity(intent);
//                                                }
//                                            }
//
//                                        }
//                                    });

                                    customerList.clear();
                                    customerList.addAll(customerList1);
                                    ladapter.notifyDataSetChanged();
                                    lstv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            final int client_id = customerList.get(customerList.size() - position).getClient_id();
                                            intent = new Intent(CustomerSimpleMessageActivity.this, CustomerDetailedMessageActivity.class);
                                            intent.putExtra("number", client_id);
                                            if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))) {
                                                intent.putExtra("kehuchiTag", "kehuchi");
                                                intent.putExtra("number", client_id);
                                            }
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    customerDao customerdao = new customerDaoImpl();
                                                    GetCustumer.customers = customerdao.queryDetailedCustomerMessage(baseClass.query_detailed_customer_message_url + client_id, null);
                                                    if ("success".equals(GetCustumer.customers.getTag())) {
                                                        List<ContactMessageEntity> contacts = customerdao.queryContactAllMessage(baseClass.find_all_contact + client_id, null);
                                                        for (int i = 0; i < contacts.size(); i++) {
                                                            if (1 == contacts.get(i).getIs_first_contact()) {
                                                                GetContact.create();
                                                                GetContact.contact = contacts.get(i);
                                                                tag = true;
                                                            }
                                                        }
                                                        if (contacts.size() == 0 || !tag) {
                                                            GetContact.create();
                                                        }
                                                        tag = false;
                                                        startActivity(intent);
                                                    } else {
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                Toast.makeText(CustomerSimpleMessageActivity.this, "数据加载失败", Toast.LENGTH_SHORT).show();
                                                            }
                                                        });
                                                    }


                                                }
                                            }).start();

                                        }
                                    });
                                }
                            });
                        }
                    }).start();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CustomerSimpleMessageActivity.this, CustomerSearchActivity.class);
                if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))) {
                    intent.putExtra("kehuchiTag", "kehuchi");
                }
                startActivity(intent);
            }
        });

    }

    private void initData() {
        loadData(AutoListView.REFRESH);

    }

    private void loadData(int refresh) {
        if (refresh==AutoListView.REFRESH){
        UpdateTextTask updateTextTask = new UpdateTextTask();
        updateTextTask.execute();
        }else if(refresh==AutoListView.LOAD){
            LoadTask loadTask = new LoadTask();
            loadTask.execute();
        }

    }
    class LoadTask extends AsyncTask<Void,Integer,Integer> {
        Message msg = handler.obtainMessage();
        @Override
        protected Integer doInBackground(Void... voids) {
            int what = 1;
            msg.what = what;
            customerDao customerdao = new customerDaoImpl();
            page=page+1;
            if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))){
                customerlist = customerdao.querySimpleCustomerMessage(baseClass.find_all_customer_url+page, null);
            }else {
                if (a == 0) {
                    customerlist = customerdao.querySimpleCustomerMessage(baseClass.query_simple_customer_message_url + page, null);
                }else{
                    customerlist=customerdao.queryMineAllCustomerMessage(baseClass.query_mine_customer_url+page,null);
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(Integer integer) {
            msg.obj = customerlist;
            handler.sendMessage(msg);
            super.onPostExecute(integer);
        }
    }
    class UpdateTextTask extends AsyncTask<Void,Integer,Integer> {
        Message msg = handler.obtainMessage();
        @Override
        protected Integer doInBackground(Void... voids) {
            int what = 0;
            msg.what = what;
            page =1;
            customerDao customerdao = new customerDaoImpl();
            if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))){
                customerlist = customerdao.querySimpleCustomerMessage(baseClass.find_all_customer_url+page, null);
            }else {
                if (a == 0) {
                    customerlist = customerdao.querySimpleCustomerMessage(baseClass.query_simple_customer_message_url + page, null);
                }else{
                    customerlist=customerdao.queryMineAllCustomerMessage(baseClass.query_mine_customer_url+page,null);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            msg.obj = customerlist;
            handler.sendMessage(msg);
            super.onPostExecute(integer);
        }
    }
        public void onRefresh() {
            loadData(AutoListView.REFRESH);
    }
        public  void onLoad(){
            loadData(AutoListView.LOAD);
        }

    public List<CustomerMessageEntity> getData() {
        customerlist = null;
        new Thread(new Runnable() {
            @Override
            public void run() {
                customerDao customerdao = new customerDaoImpl();
                if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))){
                    customerlist = customerdao.querySimpleCustomerMessage(baseClass.find_all_customer_url, null);
                }else {
                    customerlist = customerdao.querySimpleCustomerMessage(baseClass.query_simple_customer_message_url, null);
                }
                }
        }).start();
       if (customerlist!=null){
           return customerlist;
       }else{
           try {
               Thread.sleep(2000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           return customerlist;
       }
}

    @Override
    protected void onRestart() {
        super.onRestart();
        if (GetCustomerData.customers!=null){
            customerList.clear();
            customerList.addAll(GetCustomerData.customers);
            ladapter.notifyDataSetChanged();
            GetCustomerData.customers=null;
        }
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return customerList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {

            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.listview_item,null);
                holder = new ViewHolder();
                holder.item_text1 = (TextView) convertView.findViewById(R.id.listview_item_txt_name);
//                holder.item_text2= (TextView) convertView.findViewById(R.id.listview_item_txt_bz);
                holder.item_text3 = (TextView) convertView.findViewById(R.id.listview_item_createTime);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.item_text1.setText(customerList.get(customerList.size()-1-position).getClient_name());
//            holder.item_text2.setText(customerList.get(position).getDisease_category());
            if (customerList.get(customerList.size()-1-position).getCreate_time()!=null){
                SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss ");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                String time = customerList.get(customerList.size()-1-position).getCreate_time();
                long l = Long.parseLong(time);
                Date date = new Date(l);
                String create_time = sdf.format(date);
                holder.item_text3.setText(create_time);
            }
            return convertView;
        }
        class ViewHolder {
            TextView item_text1, item_text2, item_text3,item_text4;
        }
    }
}
